package com.demo.common.utils;

import lombok.SneakyThrows;

import java.io.*;

/**
 * 序列化工具
 *
 **/
public class SerializeUtil {

    @SneakyThrows
    public static Object deserialize(byte[] bytes) {
        if (bytes == null || bytes.length <= 0) {
            return null;
        }

        ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes);
        ObjectInputStream objectInputStream = new ObjectInputStream(byteStream);
        return objectInputStream.readObject();
    }

    @SneakyThrows
    public static byte[] serialize(Object object) {
        if (object == null) {
            return new byte[0];
        }
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream(128);

        if (!(object instanceof Serializable)) {
            throw new IllegalArgumentException(SerializeUtil.class.getSimpleName() + " requires a Serializable payload " +
                    "but received an object of type [" + object.getClass().getName() + "]");
        }
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteStream);
        objectOutputStream.writeObject(object);
        objectOutputStream.flush();
        return byteStream.toByteArray();
    }
}
